<?php 
header('content-type:text/html;charset=utf-8');
//2.接收信息
$act=$_GET['act'];
if($act!=='select'){
	$data=json_decode($_POST['mydata'],true);
}
if($act==='add'){
	add($data);
}elseif($act==='dele'){
	dele($data);
}elseif($act==='update'){
	update($data);
}elseif($act==='select'){
	select();
}

function database($str){
	$servername = "localhost";
	$username = "cb";
	$password = "root";
	$dbname = "demo";
	// 创建连接
	$conn = new mysqli($servername, $username, $password, $dbname);
	// Check connection
	if ($conn->connect_error) {
	    die("连接失败: " . $conn->connect_error);
	} 
	 
	$sql = $str;
	$result = $conn->query($sql);
	$conn->close();
	return $result;
}

function add($user)
{
	$sql="INSERT INTO myweight (date, weight, movement, energy) 
	VALUES ('".$user["time"]."', '".$user["weight"]."', '".$user["movement"]."', '".$user["energy"]."')";
	$ret = database($sql);
	if($ret){
		echo 'success';
	}
}

function select()
{
	$sql = "SELECT * FROM myweight";
	$ret = database($sql);
	if ($ret->num_rows > 0) {
    	$array= array();
		while($row = $ret->fetch_assoc()) {
    		array_push($array,$row);
    	}
		echo json_encode($array);
	} else {
	    echo "erorr";
	}
}